package mqs

import (
	"context"
	"github.com/zeromicro/go-zero/core/jsonx"
	"github.com/zeromicro/go-zero/core/logx"
	mqmodel "xialou_platform/app/rqueue/model"
	"xialou_platform/services/agent/rpc/agent"
	"xialou_platform/services/wallet/api/internal/svc"
)

type XiaLouUserBindAgent struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewXiaLouUserBindAgent(ctx context.Context, svcCtx *svc.ServiceContext) *XiaLouUserBindAgent {
	logx.Info("MQ: XiaLouUserBindAgent- init")
	return &XiaLouUserBindAgent{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *XiaLouUserBindAgent) Consume(_, val string) error {
	logx.Infof("XiaLouUserBindAgent->Consume :%v", val)
	var message mqmodel.XiaLouUserBindAgentModel
	err := jsonx.Unmarshal([]byte(val), &message)
	if err != nil {
		logx.WithContext(l.ctx).Error("XiaLouUserBindAgent->Consume Unmarshal err : %v , val : %s", err, val)
		return err
	}
	logx.Infof("XiaLouUserBindAgent->message :%+v", message)
	// 判断商家是否存在
	storeInfo, err := l.svcCtx.AgentRpc.StoreById(l.ctx, &agent.IdBody{Id: message.StoreId})
	if err != nil {
		logx.Errorf("查询商家错误：%+v", err)
		return err
	}
	logx.Infof("绑定商家：%+v", storeInfo)
	// 商家是否绑定销氪
	if storeInfo.AgentId > 0 {
		// 记录绑定关系
		_, err = l.svcCtx.AgentRpc.AgentUserAdd(l.ctx, &agent.AgentUser{
			AgentId:    storeInfo.AgentId,
			UserId:     message.Uid,
			Status:     1, // 绑定
			SourceType: 2, // 订单
			SourceId:   message.OrderId,
		})
		if err != nil {
			logx.Errorf("销氪绑定用户错误：%+v", err)
			return err
		}
	}
	return nil
}
